package com.example.jsonandajax.json;

import com.example.jsonandajax.pojo.Person;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTest {

    //    javaBean与json的互转
    @Test
    public void test1() {
        Person person1 = new Person(1, "li");
//        创建Gson对象实例
        Gson gson = new Gson();
//      对象转JSON
        String personJsonString = gson.toJson(person1);
        System.out.println(personJsonString);
//      JSON转对象
        Person person11 = gson.fromJson(personJsonString, Person.class);
        System.out.println(person11);
    }

    //    List与json的互转
    @Test
    public void test2() {
        List<Person> personList2 = new ArrayList<>();
        personList2.add(new Person(1,"zhang"));
        personList2.add(new Person(2,"liu"));
        //        创建Gson对象实例
        Gson gson = new Gson();
//      List转JSON
        String personJsonList = gson.toJson(personList2);
        System.out.println(personJsonList);
//      JSON转List
        List<Person> personList22 = gson.fromJson(personJsonList, new PersonListType().getType());
        System.out.println(personList22);
    }

    //    Map与json的互转
    @Test
    public void test3() {
        Map<Integer,Person> personMap3 = new HashMap<>();
        personMap3.put(1,new Person(1,"zhang"));
        personMap3.put(2,new Person(2,"liu"));
        //        创建Gson对象实例
        Gson gson = new Gson();
//      List转JSON
        String personJsonMap = gson.toJson(personMap3);
        System.out.println(personJsonMap);
//      JSON转List
//        List<Person> personMap33 = gson.fromJson(personJsonMap, new PersonMapType().getType());
        List<Person> personMap33 = gson.fromJson(personJsonMap, new TypeToken<HashMap<Integer,Person>>(){}.getType());
        System.out.println(personMap33);
    }

}
